import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Col, Form, message, Popconfirm, Row, Space } from 'antd';
// import ExportJsonExcel from 'js-export-excel';
import { useRef } from 'react';

import { delete_api, delete_batch_api, get_list_api, post_save_api } from './api';

// import { MyIcon } from '@/components/MyIcon';

export default function Page() {
  const ref = useRef<ActionType>();
  const [formAdd] = Form.useForm<TimedTaskApi.Dto>();
  const [formEdit] = Form.useForm<TimedTaskApi.Dto>();

  const columns: ProColumns<TimedTaskApi.List>[] = [
    // {
    //   dataIndex: 'index',
    //   valueType: 'indexBorder',
    //   width: 48,
    // },
    {
      title: '编号',
      width: 180,
      copyable: true,
      search: false,
      dataIndex: 'id',
      render: (_) => <a>{_}</a>,
    },
    {
      title: '是否开启',
      search: false,
      dataIndex: 'isStart',
      render: (_,row) => <span>{row.isStart==='0'?'否':'是'}</span>,
    },
    {
      title: '执行方法',
      search: false,
      dataIndex: 'methodName',
    },
    {
      title: '执行类',
      search: false,
      dataIndex: 'serviceClass',
    },
    {
      title: '执行名称',
      dataIndex: 'serviceName',
    },
    {
      title: '备注',
      search: false,
      dataIndex: 'remark',
    },
    {
      title: '创建时间',
      search: false,
      width: 180,
      dataIndex: 'createTime',
    },
    {
      title: '修改时间',
      search: false,
      width: 180,
      dataIndex: 'updateTime',
    },
    {
      title: '操作',
      align: 'left',
      width: 140,
      key: 'option',
      valueType: 'option',
      render: (_, row) => {
        return [
          <ModalForm<TimedTaskApi.Dto>
            key="edit"
            title="编辑"
            width={600}
            modalProps={{
              destroyOnClose: true,
              maskClosable: false,
              onCancel: () => {},
            }}
            trigger={
              <a
                onClick={() => {
                  setTimeout(() => {
                    // 延迟填入数据，为了防止from未创建
                    row.isStart=row.isStart==='1'
                    formEdit.setFieldsValue(row);
                  }, 100);
                }}
              >
                编辑
              </a>
            }
            form={formEdit}
            autoFocusFirstInput
            submitTimeout={2000}
            onFinish={async (values) => {
              console.log(values);
              values.id = row.id;
              values.isStart=values.isStart?'1':'0';
              const res = await post_save_api(values);
              console.log(res);
              if (res.success) {
                // 刷新

                ref.current?.reload();
                message.success('提交成功');
              }

              return res.success;
            }}
          >
            <Row gutter={16}>
              <Col span={24}>
                <ProFormText
                  rules={[{ required: true, message: '请输入执行名称' }]}
                  placeholder="请输入执行名称"
                  name="serviceName"
                  label="执行名称"
                />
              </Col>
              <Col span={24}>
                <ProFormText
                  rules={[{ required: true, message: '请输入执行类' }]}
                  placeholder="请输入执行类"
                  name="serviceClass"
                  label="执行类"
                />
              </Col>
              <Col span={24}>
                <ProFormText
                  rules={[{ required: true, message: '请输入执行方法' }]}
                  placeholder="请输入执行方法"
                  name="methodName"
                  label="执行方法"
                />
              </Col>
             
              <Col span={24}>
                <ProFormText
                  rules={[{ required: true, message: '请输入执行时间' }]}
                  placeholder="请输入执行时间"
                  name="cron"
                  label="执行时间"
                />
              </Col>

              <Col span={24}>
                <ProFormSwitch name="isStart" label="是否开启" />
              </Col>

              <Col span={24}>
                <ProFormTextArea placeholder="请输入备注" name="remark" label="备注" />
              </Col>
            </Row>
          </ModalForm>,
          <Popconfirm
            key="delete"
            title="删除"
            description="确认删除此条数据?"
            onConfirm={async () => {
              console.log(row.id);
              const res = await delete_api(row.id);
              if (res.success) {
                // 刷新
                ref.current?.reload();
                message.success('删除成功');
              }
            }}
            onCancel={() => {
              message.error('删除已取消');
            }}
            okText="是"
            cancelText="否"
          >
            <a style={{ color: '#F56C6C' }}>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<TimedTaskApi.List>
        actionRef={ref}
        request={async (params = {}) => {
          // console.log(params);
          const columnFilters: any = {};
          Object.keys(params).forEach((key) => {
            if (key !== 'current' && key !== 'pageSize') {
              columnFilters[key] = {
                eq: '%',
                name: key,
                value: params[key],
              };
            }
          });
          const res = await get_list_api({
            columnFilters: columnFilters,
            pageNum: params?.current ?? 1,
            pageSize: params?.pageSize ?? 10,
          });

          return {
            page: params?.current,
            data: res.data.records,
            success: true,
            total: res.data.total,
          };
        }}
        rowKey="id"
        pagination={{
          pageSize: 10,
        }}
        columns={columns}
        rowSelection={
          {
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            // selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          }
        }
        tableAlertOptionRender={({ selectedRowKeys, onCleanSelected }) => {
          return (
            <Space size={16}>
              <Popconfirm
                key="delete"
                title="批量删除"
                description="确认删除这些数据?"
                onConfirm={async () => {
                  const res = await delete_batch_api(selectedRowKeys);
                  if (res.success) {
                    onCleanSelected();
                    // 刷新
                    ref.current?.reload();
                    message.success('删除成功');
                  }
                }}
                onCancel={() => {
                  message.error('删除已取消');
                }}
                okText="是"
                cancelText="否"
              >
                <a style={{ color: '#F56C6C' }}>批量删除</a>
              </Popconfirm>
            </Space>
          );
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <ModalForm<TimedTaskApi.Dto>
            key="add"
            title="新增"
            width={600}
            modalProps={{
              destroyOnClose: true,
              maskClosable: false,
              onCancel: () => {},
            }}
            trigger={
              <Button type="primary" key="primary">
                新增
              </Button>
            }
            form={formAdd}
            autoFocusFirstInput
            submitTimeout={2000}
            onFinish={async (values) => {
              console.log(values);
              values.isStart=values.isStart?'1':'0'
              const res = await post_save_api(values);
              console.log(res);
              if (res.success) {
                // 刷新
                ref.current?.reload();
                message.success('提交成功');
              }

              return res.success;
            }}
          >
            <Row gutter={16}>
              <Col span={24}>
                <ProFormText
                  rules={[{ required: true, message: '请输入执行名称' }]}
                  placeholder="请输入执行名称"
                  name="serviceName"
                  label="执行名称"
                />
              </Col>
              <Col span={24}>
                <ProFormText
                  rules={[{ required: true, message: '请输入执行类' }]}
                  placeholder="请输入执行类"
                  name="serviceClass"
                  label="执行类"
                />
              </Col>
              <Col span={24}>
                <ProFormText
                  rules={[{ required: true, message: '请输入执行方法' }]}
                  placeholder="请输入执行方法"
                  name="methodName"
                  label="执行方法"
                />
              </Col>
              
              <Col span={24}>
                <ProFormText
                  rules={[{ required: true, message: '请输入执行时间' }]}
                  placeholder="请输入执行时间"
                  name="cron"
                  label="执行时间"
                />
              </Col>

              <Col span={24}>
                <ProFormSwitch name="isStart" label="是否开启" />
              </Col>

              <Col span={24}>
                <ProFormTextArea placeholder="请输入备注" name="remark" label="备注" />
              </Col>
            </Row>
          </ModalForm>,
          // <Tooltip key="excel" placement="top" title={'导出Excel'}>
          //   <MyIcon
          //     type="icon-Microsoft-Excel"
          //     style={{ fontSize: 18 }}
          //     onClick={() => {
          //       console.log('导出Excel');
          //     }}
          //   ></MyIcon>
          // </Tooltip>,
        ]}
      />
    </PageContainer>
  );
}
